package com.wechat.backend.service.impl;

import com.wechat.backend.entity.Friend;
import com.wechat.backend.entity.User;
import com.wechat.backend.repository.FriendRepository;
import com.wechat.backend.repository.UserRepository;
import com.wechat.backend.service.FriendService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class FriendServiceImpl implements FriendService {

    @Autowired
    private FriendRepository friendRepository;

    @Autowired
    private UserRepository userRepository;

    @Override
    public List<Friend> getReceivedRequests(Integer userId) {
        return friendRepository.findByFriendIdAndStatus(userId, "pending");
    }

    @Override
    public List<Friend> getSentRequests(Integer userId) {
        return friendRepository.findByUserIdAndStatus(userId, "pending");
    }

    @Override
    public Map<String, Object> acceptRequest(Integer requestId) {
        Map<String, Object> result = new HashMap<>();
        Optional<Friend> optional = friendRepository.findById(Long.valueOf(requestId));
        if (!optional.isPresent()) {
            result.put("success", false);
            result.put("message", "请求不存在");
            return result;
        }
        Friend request = optional.get();
        if (!"pending".equals(request.getStatus())) {
            result.put("success", false);
            result.put("message", "请求已处理");
            return result;
        }
        // 更新状态为 accepted
        request.setStatus("accepted");
        friendRepository.save(request);

        // 互加好友（对方也有一条记录）
        if (friendRepository.findByUserIdAndFriendId(request.getFriendId(), request.getUserId()) == null) {
            Friend reverse = new Friend();
            reverse.setUserId(request.getFriendId());
            reverse.setFriendId(request.getUserId());
            reverse.setStatus("accepted");
            reverse.setCreatedAt(new Date());
            friendRepository.save(reverse);
        }

        result.put("success", true);
        result.put("message", "已同意好友请求");
        return result;
    }

    @Override
    public Map<String, Object> rejectRequest(Integer requestId) {
        Map<String, Object> result = new HashMap<>();
        Optional<Friend> optional = friendRepository.findById(Long.valueOf(requestId));
        if (!optional.isPresent()) {
            result.put("success", false);
            result.put("message", "请求不存在");
            return result;
        }
        Friend request = optional.get();
        if (!"pending".equals(request.getStatus())) {
            result.put("success", false);
            result.put("message", "请求已处理");
            return result;
        }
        // 更新状态为 rejected
        request.setStatus("rejected");
        friendRepository.save(request);

        result.put("success", true);
        result.put("message", "已拒绝好友请求");
        return result;
    }

    @Override
    public List<User> getFriends(Integer userId) {
        // 获取所有已接受的好友关系
        List<Friend> friends = friendRepository.findByUserIdAndStatus(userId, "accepted");

        // 提取好友ID列表并转换为 Long 类型
        List<Long> friendIds = friends.stream()
                .map(f -> f.getFriendId().longValue())
                .collect(Collectors.toList());

        // 查询好友用户信息
        if (friendIds.isEmpty()) {
            return new ArrayList<>();
        }

        return userRepository.findAllById(friendIds);
    }
} 